package com.mx.kn.cstf2.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import kn.cstf2.global.Utils.CstF2Exception;
import kn.cstf2.transition.Bean.TransitionBean;


import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.mx.kn.cstf2.actions.padre.Transition;
import com.mx.kn.cstf2.dto.ComentarioDto;
import com.mx.kn.cstf2.dto.ForoDto;
import com.mx.kn.cstf2.dto.UsuarioDto;
import com.mx.kn.cstf2.dts.FilesUploadDts;
import com.mx.kn.cstf2.service.ForoService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


@Component("foroAction")
@Scope(value="session")

public class ForoAction extends ActionSupport implements ServletRequestAware{
	@Autowired ForoService foroService;
	private File myFile;
	private String myFileFileName;
	private List<ForoDto> listaTopics;
	private List<ComentarioDto> comentarios;
	private int id;
	private int idTopico;
	private int idComentario;
	private int idForo;
	private String reply;
	private File imgReplyFile;
	private File fileReplyFile;
	private String imgReplyFileFileName;
	private String fileReplyFileFileName;
	private String nameFileDownload;
	private String ZIP = "zip";
	private String ERROR_DOWN = "errorFileTransition";
	private String filePath = FilesUploadDts.RUTA_FILES+FilesUploadDts.RUTA_FILES_FORO;
	private HttpServletRequest servletRequest;
	private InputStream inputStream;
	

	
	
	public String execute() 
	{
		ActionContext contexto = ActionContext.getContext();
   	 	Map<String, Object> sesion = contexto.getSession();
   	 	Transition transition = new Transition();
   	 	transition = ((Transition) sesion.get("transition"));
     
	     if(transition instanceof TransitionFS){
	    	 transition = (TransitionFS)transition;
	     }else if(transition instanceof TransitionFO){
	    	 transition = (TransitionFO) transition;
	     }else if(transition instanceof TransitionFA){
	    	 transition =(TransitionFA)transition;
	     }
   	 
		
		try {
			listaTopics = new ArrayList<ForoDto>();
	        listaTopics = foroService.getTopics(transition.getTransitionBeanM());
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
        return SUCCESS;
    }

	
	public String viewItem(){
		try {
			this.setComentarios(foroService.getListComentarios(id, idForo));
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	
	public String vistaFile(){
		return SUCCESS;
	}
	
	public String infoTopic(){
		try {
			this.setComentarios(foroService.getListComentarios(id, idForo));
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	public String saveAttachments() throws Exception{
		
		String guardaName="";
		File fileToCreate = null;
//		String urlImg="";
//		String urlFile="";
//		boolean isImage = (myFileFileName.indexOf(".jpg")  != -1 || (myFileFileName.indexOf(".png")  != -1 ) )? true:false;
		 ActionContext contexto = ActionContext.getContext();
		 Map<String, Object> sesion = contexto.getSession();
		 Transition transition = (Transition) sesion.get("transition");
		UsuarioDto usuario= (UsuarioDto) sesion.get("usuarioSession");
		 
		 ComentarioDto comentario = foroService.getComentartio(idTopico, idComentario, transition.getTransitionBeanM());
		 if((myFileFileName.indexOf(".jpg")  != -1 || (myFileFileName.indexOf(".png")  != -1 ) )){
			//es imagen revisar si el comentario ya cueta con imagen
			if(comentario.getImg() != null){
				sesion.put("result", "imgExist");
				return SUCCESS;
			}else{
				String filePath = servletRequest.getSession().getServletContext().getRealPath("/")+"imagenescomentarios";
				guardaName = transition.getTransitionBeanM().getId() + "_" + idForo + "_" + idTopico + "_" + idComentario + myFileFileName;
				fileToCreate = new File(filePath,guardaName);
				FileUtils.copyFile(this.myFile, fileToCreate);
				foroService.updateUrlImgComment(idTopico, idComentario,idForo, guardaName, usuario.getUsername());
				sesion.put("result", "OK");
				return SUCCESS;
			}
		}else{
			if(comentario.getFile() != null){
				sesion.put("result", "fileExist");
				return SUCCESS;
			}else{
				guardaName =  transition.getTransitionBeanM().getId() + "_" + idForo + "_" + idTopico + "_" + idComentario + myFileFileName;
				fileToCreate = new File(this.filePath,guardaName);
				FileUtils.copyFile(this.myFile, fileToCreate);
				foroService.updateUrlFileComment(idTopico, idComentario,idForo, guardaName,usuario.getUsername());
				sesion.put("result", "OK");
				return SUCCESS;
			}
			
		}
			
		
		
//		if(this.getImgReplyFile() != null){
//			//
//			
//			guardaName = this.getImgReplyFileFileName();
//			fileToCreate = new File(filePath,guardaName);
//			FileUtils.copyFile(this.getImgReplyFile(), fileToCreate);
//			foroService.updateUrlImgComment(idTopico, idComentario, guardaName);
//
//		}
//		
//		
//		if(this.getFileReplyFile() != null){
//			//
//			guardaName = this.getFileReplyFileFileName();
//			fileToCreate = new File(filePath,guardaName);
//			FileUtils.copyFile(this.getFileReplyFile(), fileToCreate);
//			foroService.updateUrlFileComment(idTopico, idComentario, guardaName);
//
//		}
	
		
//		return SUCCESS;
	}
	public String saveReply() throws Exception{
		ActionContext contexto = ActionContext.getContext();
		Map<String, Object> sesion = contexto.getSession();
		UsuarioDto usuario= (UsuarioDto) sesion.get("usuarioSession");

		try {
			if(idTopico == 0){
				foroService.insertComment(id, idComentario,idForo, reply, usuario.getUsername());
			}else{
				foroService.insertComment(idTopico, idComentario,idForo, reply, usuario.getUsername());
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	public String insertComment() throws Exception{
		ActionContext contexto = ActionContext.getContext();
		Map<String, Object> sesion = contexto.getSession();
		UsuarioDto usuario = (UsuarioDto) sesion.get("usuarioSession");
		foroService.insertComment(id, 0,idForo, reply, usuario.getUsername());
		
		return SUCCESS;
	}
	
	
	public String afterInsertFile(){
		return SUCCESS;
	}
	
	
	public String saveIds(){
		return SUCCESS;
	}
	
	public String downloadFile(){
	       try {
	           File file = new File(filePath+"\\"+this.getNameFileDownload());
	            	            
	            this.setInputStream(new FileInputStream(file));

	            if (this.getInputStream() == null) {
	                throw new CstF2Exception("No existe el archivo");
	            }

	        } catch (IOException ex) {
//	            java.util.logging.Logger.getLogger(TransitionClient.class.getName()).log(Level.SEVERE, null, ex);
	            addFieldError("Error al obtener el archivo", "Ocurrio un Error: error al descargar archivo. \n" + ex.getMessage());
	            return ERROR_DOWN;
	        } catch (CstF2Exception ex) {
	            
	            addFieldError("KnkeyIncorrecta", ex.getMessage());
	            return ERROR_DOWN;
	        }
	        return ZIP;
	}
	
	
	public List<ForoDto> getListaTopics() {
		return listaTopics;
	}

	public void setListaTopics(List<ForoDto> listaTopics) {
		this.listaTopics = listaTopics;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}


	public List<ComentarioDto> getComentarios() {
		return comentarios;
	}


	public void setComentarios(List<ComentarioDto> comentarios) {
		this.comentarios = comentarios;
	}


	public int getIdTopico() {
		return idTopico;
	}


	public void setIdTopico(int idTopico) {
		this.idTopico = idTopico;
	}


	public int getIdComentario() {
		return idComentario;
	}


	public void setIdComentario(int idComentario) {
		this.idComentario = idComentario;
	}


	public String getReply() {
		return reply;
	}


	public void setReply(String reply) {
		this.reply = reply;
	}


	public File getImgReplyFile() {
		return imgReplyFile;
	}


	public void setImgReplyFile(File imgReplyFile) {
		this.imgReplyFile = imgReplyFile;
	}


	public File getFileReplyFile() {
		return fileReplyFile;
	}


	public void setFileReplyFile(File fileReplyFile) {
		this.fileReplyFile = fileReplyFile;
	}


	public String getImgReplyFileFileName() {
		return imgReplyFileFileName;
	}


	public void setImgReplyFileFileName(String imgReplyFileFileName) {
		this.imgReplyFileFileName = imgReplyFileFileName;
	}


	public String getFileReplyFileFileName() {
		return fileReplyFileFileName;
	}


	public void setFileReplyFileFileName(String fileReplyFileFileName) {
		this.fileReplyFileFileName = fileReplyFileFileName;
	}


	public String getFilePath() {
		return filePath;
	}


	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	
	

	public String getNameFileDownload() {
		return nameFileDownload;
	}


	public void setNameFileDownload(String nameFileDownload) {
		this.nameFileDownload = nameFileDownload;
	}


	@Override
	public void setServletRequest(HttpServletRequest request) {
		servletRequest = request;
	}


	public InputStream getInputStream() {
		return inputStream;
	}


	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}




	public File getMyFile() {
		return myFile;
	}


	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}


	public String getMyFileFileName() {
		return myFileFileName;
	}


	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}


	public int getIdForo() {
		return idForo;
	}


	public void setIdForo(int idForo) {
		this.idForo = idForo;
	}


	



	
	


	
	
}
